import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Modal, Spin, Tree } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import type { TreeProps } from 'antd/es/tree';
import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { addRole, roleList, treeList, treeUpdate, updateRule, listMenu } from './service';
import type { Children, TableListItem, TableListPagination } from './data';
import type { RootObject } from '../menu/data'
import TreeTag from '@/components/TreeTag'

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: TableListItem) => {
    const hide = message.loading('正在添加');

    try {
        await addRole({ ...fields });
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields: any, currentRow?: TableListItem) => {
    const hide = message.loading('正在配置');

    try {
        await updateRule({
            ...currentRow,
            ...fields,
        });
        hide();
        message.success('配置成功');
        return true;
    } catch (error) {
        hide();
        message.error('配置失败请重试！');
        return false;
    }
};

const TableList: React.FC = () => {
    /** 新建窗口的弹窗 */
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    /** 分布更新窗口的弹窗 */
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

    const [authVisible, handleAuthVisible] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<TableListItem>();
    const [treeData, setTreeData] = useState<RootObject[]>([]);
    const [checkedKeys, setCheckedKeys] = useState<number[]>([]);
    // 配置权限树控件加载
    const [loading, setLoading] = useState<boolean>(false);

    useEffect(() => {
        const getTreeData = async () => {
            let data: Children[] = await listMenu({ tree: true })
            setTreeData(data)
        }
        getTreeData()
    }, [])

    const columns: ProColumns<TableListItem>[] = [
        {
            title: '名称',
            dataIndex: 'name',
            valueType: 'textarea',
        },
        {
            title: '状态',
            dataIndex: 'status',
            hideInForm: true,
            valueEnum: {
                1: {
                    text: '正常',
                    status: 'Processing',
                },
                2: {
                    text: '禁用',
                    status: 'Error',
                },
            },
        },
        {
            title: '创建时间',
            dataIndex: 'created_at',
            search: false,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            width: 200,
            render: (_, record) => [
                <a
                    key="config"
                    onClick={() => {
                        handleUpdateModalVisible(true);
                        setCurrentRow(record);
                    }}
                >
                    编辑
                </a>,
                <a
                    key="auth"
                    onClick={async () => {
                        setCurrentRow(record);
                        setLoading(true)
                        handleAuthVisible(true);
                        let data: number[] = await treeList({ role_id: record?.guid })
                        setCheckedKeys(data)
                        setLoading(false)
                    }}
                >
                    配置权限
                </a>,
            ],
        },
    ];


    const onSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
        console.log('selected', selectedKeys, info);
    };

    const onCheck: TreeProps['onCheck'] = (keys, info) => {
        let now = info.node
        if (info.checked && now.pid != 0 && !checkedKeys.includes(now.pid)) {
            message.error('请保证其父级已被选中，不然选择无效');
            return
        }
        treeUpdate({ role_id: currentRow?.guid, auth_id: now?.guid, type: info.checked ? 1 : 2 })

        setCheckedKeys(keys.checked)
    };

    return (
        <PageContainer>
            <ProTable<TableListItem, TableListPagination>
                headerTitle="查询表格"
                actionRef={actionRef}
                rowKey="id"
                search={{
                    labelWidth: 120,
                }}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            handleModalVisible(true);
                        }}
                    >
                        <PlusOutlined /> 新建
                    </Button>,
                ]}
                request={roleList}
                columns={columns}
            />


            {/* 新建modal */}
            <ModalForm
                title="新建"
                width="600px"
                visible={createModalVisible}
                onVisibleChange={handleModalVisible}
                modalProps={{
                    destroyOnClose: true
                }}
                onFinish={async (value) => {
                    const success = await handleAdd(value as TableListItem);
                    if (success) {
                        handleModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
            >
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: '名称为必填项',
                        },
                    ]}
                    width="md"
                    name="name"
                    label="角色名称"
                />
            </ModalForm>

            <ModalForm
                title="编辑"
                width="600px"
                visible={updateModalVisible}
                onVisibleChange={handleUpdateModalVisible}
                initialValues={{
                    ...currentRow,
                    status: currentRow ? currentRow.status + '' : '',
                }}
                modalProps={{
                    destroyOnClose: true
                }}
                onFinish={async (value) => {
                    const success = await handleUpdate(value, currentRow);

                    if (success) {
                        handleUpdateModalVisible(false);
                        setCurrentRow(undefined);

                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
            >
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: '名称为必填项',
                        },
                    ]}
                    width="md"
                    name="name"
                    label="角色名称"
                />
                <ProFormSelect
                    name="status"
                    width="md"
                    label="状态"
                    valueEnum={{
                        '1': '正常',
                        '2': '禁用',
                    }}
                />
            </ModalForm>

            <Modal
                visible={authVisible}
                title="分配权限"
                onCancel={() => {
                    handleAuthVisible(false)
                }}
                footer={null}
            >
                <Spin spinning={loading}>
                    <Tree
                        checkable
                        blockNode
                        selectable={false}
                        checkStrictly
                        defaultExpandAll
                        checkedKeys={checkedKeys}
                        fieldNames={{ key: 'guid', title: 'name' }}
                        onSelect={onSelect}
                        onCheck={onCheck}
                        treeData={treeData}
                        titleRender={(data) => (
                            <TreeTag title={data?.name} type={data.type} />
                        )}
                    />

                </Spin>

            </Modal>

        </PageContainer>
    );
};

export default TableList;
